package com.boot.mall.member.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.common.vo.MemberResponseVo;
import com.boot.mall.member.dao.MemberLevelDao;
import com.boot.mall.member.exception.EmailExistException;
import com.boot.mall.member.exception.UserNameExistException;
import com.boot.mall.member.utils.Encrypt;
import com.boot.mall.member.vo.MemberLoginVo;
import com.boot.mall.member.vo.MemberRegisterVo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.common.utils.PageUtils;

import com.boot.mall.member.dao.MemberDao;
import com.boot.mall.member.entity.MemberEntity;
import com.boot.mall.member.service.MemberService;

import javax.annotation.Resource;


@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils pageMember(Map<String, Object> params) {
        // 获取参数
        long current = Integer.parseInt(params.get("page").toString());
        long limit = Integer.parseInt(params.get("limit").toString());
        // 创建分页对象
        Page<MemberEntity> page = new Page<>(current,limit);
        // 执行查询
        baseMapper.selectPage(page,null);
        // 结果封装
        PageUtils pageUtils = new PageUtils(page.getRecords(),(int)page.getTotal(),(int)page.getSize(),(int)current);
        return pageUtils;
    }

    @Override
    public void registerMember(MemberRegisterVo vo) {
        // 检查用户名是否唯一
        this.checkUserNameExist(vo.getUserName());
        // 检查邮箱是否唯一
        this.checkEmailExist(vo.getEmail());
        // 简单校验通过，设置用户默认信息注册
        MemberEntity memberEntity = new MemberEntity();
        // 设置会员的默认等级为普通会员
        memberEntity.setLevelId(memberLevelDao.getDefaultLevel());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setEmail(vo.getEmail());
        // 对用户输入的密码进行加密处理
        String encryptPassword = Encrypt.EncryptPassword(vo.getPassword());
        System.out.println("加密后密码为:" + encryptPassword);
        memberEntity.setPassword(encryptPassword);

        memberEntity.setCreateTime(new Date());

        // 注册
        this.save(memberEntity);
        System.out.println(vo.getUserName() + "用户注册成功");
    }

    // 校验邮箱是否以及被使用
    @Override
    public void checkEmailExist(String email) {
        MemberEntity member = getOne(new QueryWrapper<MemberEntity>().eq("email", email));
        if (member != null) {
            // 存在则抛出异常
            throw new EmailExistException();
        }
    }

    // 校验用户名是否存在
    @Override
    public void checkUserNameExist(String userName) {
        MemberEntity member = this.getOne(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (member != null) {
            // 存在抛出异常
            throw new UserNameExistException();
        }
    }

    // TODO 可以使用邮箱登录
    @Override
    public String loginMember(MemberLoginVo vo) {
        // 根据用户名密码从数据库查询用户信息
        MemberEntity memberEntity = this.getOne(new QueryWrapper<MemberEntity>().eq("username", vo.getLoginAccount()));
        // 用户信息为空，用户名输入错误
        if (memberEntity == null){
            return "用户名输入错误";
        }
        // 用户信息存在，比对用户密码
        // 将用户输入的密码进行同样的算法加密，再进行比对
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String md5Hex = DigestUtils.md5Hex(vo.getPassword());   //信息摘要
        // 和数据库查询的密码进行比对，第一个参数是此时用户输入密码加密，第二个参数是数据库查询到的密码
        boolean matches = encoder.matches(md5Hex, memberEntity.getPassword());
        if (matches){
            System.out.println("比对成功，密码正确");
            return "success";
        }else {
            return "密码错误";
        }
    }

    /**
     * 微博第三方用户登录
     * @return
     * @param vo
     */
    @Override
    public MemberResponseVo authRegister(MemberResponseVo vo) {
        // vo中含有uid，username,nickname
        MemberEntity registerMember = new MemberEntity();
        // 设置注册用户的基本信息
        registerMember.setUid(vo.getUid());
        registerMember.setUsername(vo.getUsername());
        registerMember.setNickname(vo.getNickname());
        registerMember.setLevelId(memberLevelDao.getDefaultLevel());
        registerMember.setCreateTime(new Date());

        this.save(registerMember);
        // 返回的用户登录信息
        MemberResponseVo returnUser = new MemberResponseVo();

        returnUser.setId(registerMember.getId());
        BeanUtils.copyProperties(registerMember,returnUser);

        System.out.println(returnUser);

        return returnUser;
    }

    // 根据用户uid查询数据库中的用户信息
    @Override
    public MemberResponseVo getMemberInfo(String uid) {
        MemberEntity member = this.getOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        MemberResponseVo responseVo = new MemberResponseVo();
        if (member != null){
            responseVo.setId(member.getId());
            responseVo.setUid(uid);
            responseVo.setLevelId(member.getLevelId());
            responseVo.setUsername(member.getUsername());
            responseVo.setNickname(member.getNickname());
            return responseVo;
        }
        return null;
    }
}